# main.py
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from neo4j import GraphDatabase
import json

app = FastAPI()
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"])

# === 配置你的 Neo4j 连接 ===
NEO4J_URI = "bolt://localhost:7687"
NEO4J_USER = "neo4j"
NEO4J_PASSWORD = "fyx123"  # <--- 根据文档，密码是 fyx123

driver = GraphDatabase.driver(NEO4J_URI, auth=(NEO4J_USER, NEO4J_PASSWORD))

# === API 1: 获取全局统计信息 ===
@app.get("/stats")
def get_stats():
    # 查询所有节点数、边数和节点标签
    query = """
    MATCH (n)
    OPTIONAL MATCH ()-[r]->()
    RETURN 
        count(DISTINCT n) AS node_count,
        count(r) AS edge_count,
        collect(DISTINCT labels(n)[0]) AS node_labels
    """
    with driver.session() as session:
        record = session.run(query).single()
        return {
            "node_count": record["node_count"],
            "edge_count": record["edge_count"],
            "labels": record["node_labels"]
        }

# === API 2: 获取图谱数据（用于 Cytoscape.js 可视化）===
@app.get("/graph")
def get_graph(limit: int = 200):
    # 查询所有节点和边，返回用于前端可视化的格式
    query = """
    MATCH (n)-[r]->(m)
    RETURN 
        id(n) AS source_id,
        labels(n)[0] AS source_label,
        id(m) AS target_id,
        labels(m)[0] AS target_label,
        type(r) AS rel_type,
        // 选择一个属性作为节点显示标签，优先使用 id 或其他唯一标识
        coalesce(n.id, n.policy_id, n.claim_id, n.record_id, n.inst_id, toString(id(n))) AS source_name,
        coalesce(m.id, m.policy_id, m.claim_id, m.record_id, m.inst_id, toString(id(m))) AS target_name
    LIMIT $limit
    """
    with driver.session() as session:
        result = session.run(query, limit=limit)
        nodes = {}
        edges = []
        for record in result:
            src_id = record["source_id"]
            tgt_id = record["target_id"]
            
            # 构建节点对象，包含所有属性（可用于详情展示）
            # 这里假设我们还想获取一些关键属性，可以扩展查询
            source_node_query = f"MATCH (n) WHERE id(n) = {src_id} RETURN properties(n) AS props"
            target_node_query = f"MATCH (n) WHERE id(n) = {tgt_id} RETURN properties(n) AS props"
            
            # 为了性能，这里简化处理，只使用查询中已有的信息
            # 如果需要完整属性，可以为每个节点单独查询或在主查询中 JOIN
            nodes[src_id] = {
                "id": src_id,
                "label": record["source_name"],
                "type": record["source_label"]
            }
            nodes[tgt_id] = {
                "id": tgt_id,
                "label": record["target_name"],
                "type": record["target_label"]
            }
            
            edges.append({
                "source": src_id,
                "target": tgt_id,
                "label": record["rel_type"]
            })
        return {"nodes": list(nodes.values()), "edges": edges}

# === API 3: 获取节点类型分布（用于 F 区域：产业对比图，这里改为节点类型对比）===
@app.get("/industry-distribution")
def get_industry_dist():
    # 查询每种节点类型的数量
    query = """
    MATCH (n)
    RETURN 
        labels(n)[0] AS node_type,
        count(*) AS count
    ORDER BY count DESC
    """
    with driver.session() as session:
        result = session.run(query)
        return [{"name": r["node_type"], "value": r["count"]} for r in result]

# === API 4: 获取关系类型分布（用于 H 区域：团伙网络信息表）===
@app.get("/relation-distribution")
def get_relation_dist():
    # 查询每种关系类型的数量
    query = """
    MATCH ()-[r]->()
    RETURN 
        type(r) AS relation,
        count(*) AS count
    ORDER BY count DESC
    LIMIT 10
    """
    with driver.session() as session:
        result = session.run(query)
        return [{"relation": r["relation"], "count": r["count"]} for r in result]

# === API 5: 获取分析摘要（模拟数据，可根据需要替换为 GDS 算法结果）===
@app.get("/analysis-summary")
def get_summary():
    # 根据你的图谱特点生成摘要
    # 这里是示例，你可以根据 GDS 算法结果或聚合查询来动态生成
    summary_text = (
        "本保险欺诈知识图谱共包含多个实体类型（Person, Policy, Claim, MedicalRecord, Institution）"
        "和多种关系（SELLS, APPLY_FOR, HAS_CLAIM 等）。"
        "分析发现，某些医生、医疗机构和客户之间存在异常高频的就诊和理赔关联，"
        "建议重点关注 Claim 节点中的 'is_fraud' 标签为 True 的案例。"
    )
    return {"summary": summary_text}

# 添加一个根路径，方便测试
@app.get("/")
def read_root():
    return {"message": "Insurance Fraud Knowledge Graph Analysis API is running!"}